//
//  HJPayPosswordController.m
//  KaiChat
//
//  Created by lx on 2024/1/25.
//

#import "HJPayPasswordController.h"
#import "QMUITextField.h"
#import "QMUIButton.h"
#import "HJMinePresent.h"
#import "HJUserModel.h"
#import "HJIM.h"
#import "HJDecimalPadKeyboard.h"
#import "HJPasswordCodeView.h"

@interface HJPayPasswordController ()<HJPasswordCodeViewDelegate>

@property (nonatomic, weak) UIView *contentView;
@property (nonatomic, weak) UIView *maskView;
@property (nonatomic, weak) HJStyle1Button *OKButton;
@property (nonatomic, weak) HJPasswordCodeView *codeView;
@property (nonatomic, assign) NSInteger lastTime;
@property (nonatomic, assign) NSInteger callType;


@end

@implementation HJPayPasswordController


- (void)showInController:(UIViewController *)controller {
    [controller presentViewController:self animated:NO completion:nil];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.callType = 0;
    [IQKeyboardManager sharedManager].enable = NO;
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = NO;
    
    self.view.backgroundColor = UIColor.clearColor;
    
    UIView *maskView = [[UIView alloc] initWithFrame:self.view.bounds];
    maskView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
    [self.view addSubview:maskView];
    
    UIView *contentView = [UIView addToView:maskView];
    contentView.backgroundColor = UIColor.whiteColor;
    contentView.frame = CGRectMake(0, KScreenHeight - 192, KScreenWidth, 192);
    
    UIBezierPath *bezierPath = [UIBezierPath bezierPathWithRoundedRect:contentView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(20, 20)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = contentView.bounds;
    maskLayer.path = bezierPath.CGPath;
    contentView.layer.mask = maskLayer;
    
    UIView *topView = [UIView addToView:contentView];
    topView.backgroundColor = UIColor.whiteColor;
    topView.frame = CGRectMake(0, 0, KScreenWidth, 50);
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.offset(50);
        make.left.right.offset(0);
        make.top.offset(0);
    }];
    
    QMUIButton *closeButton = [QMUIButton addToView:topView];
    [closeButton addTarget:self action:@selector(didClickDismissButton) forControlEvents:UIControlEventTouchUpInside];
    [closeButton setImage:[UIImage imageNamed:@"nav_close"] forState:UIControlStateNormal];
    [closeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.width.height.offset(30);
        make.left.offset(leftRightMargin);
    }];
    
    UILabel *titleLabel = [UILabel lableWithSuperView:topView font:UIFontMediumMake(15) color:UIColor.blackColor title:@"Kai Pay" textAlignment:NSTextAlignmentLeft];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.offset(0);
    }];
    
    UILabel *subTitleLabel = [UILabel lableWithSuperView:contentView font:UIFontMediumMake(13) color:UIColor.tj_333333Color title:@"Verify Password" textAlignment:NSTextAlignmentLeft];
    [subTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(leftRightMargin);
        make.top.equalTo(topView.mas_bottom).offset(10);
    }];
    
    HJDecimalPadKeyboard *decimalPadKeyboard = [HJDecimalPadKeyboard keyboard];
    decimalPadKeyboard.backgroundColor = UIColor.whiteColor;
    HJPasswordCodeView *codeView = [[HJPasswordCodeView alloc] initWithCount:6 margin:7].addTo(contentView);
    codeView.delegate = self;
    codeView.secureTextEntry = YES;
    codeView.backgroundColor = UIColor.whiteColor;
    codeView.textField.inputView = decimalPadKeyboard;
    [codeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(leftRightMargin);
        make.top.equalTo(subTitleLabel.mas_bottom).offset(15);
        make.height.offset(50);
    }];
    
    QMUIButton *forgetPasswordButton = [QMUIButton buttonWithSuperView:contentView font:UIFontMake(13) color:UIColor.tj_8667FEColor title:@"Change or forget password？"];
    [forgetPasswordButton sizeToFit];
    [forgetPasswordButton addTarget:self action:@selector(didClickForgetPasswordButton) forControlEvents:UIControlEventTouchUpInside];
    [forgetPasswordButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(codeView.mas_bottom).offset(15);
        make.width.offset(forgetPasswordButton.tj_width);
        make.height.offset(forgetPasswordButton.tj_height);
        make.right.inset(leftRightMargin);
    }];
    
    _maskView = maskView;
    _contentView = contentView;
    _codeView = codeView;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlerKeyboardWillShowNotification:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlerKeyboardWillHideNotification:) name:UIKeyboardWillHideNotification object:nil];
    dispatch_async_main_queue(^{
        [self.codeView.textField becomeFirstResponder];
    });
}

- (void)didClickForgetPasswordButton {
    self.callType = 2;
    [self.codeView.textField resignFirstResponder];
}

- (void)didClickDismissButton {
    [self.codeView.textField resignFirstResponder];
}

- (void)didClickCancelButton {
    [self.codeView.textField resignFirstResponder];
}

- (void)didClickOKButton {
    
}

- (void)textDidChange:(HJPasswordCodeView *)passwordCodeView text:(NSString *)text {
    
    if (text.length == 6) {
        //判断2s之内只能请求一次
        NSTimeInterval currentTimeInterval = [NSDate date].timeIntervalSince1970;
        if (currentTimeInterval - _lastTime < 2) {
            return;
        }
        _lastTime = currentTimeInterval;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(300 * NSEC_PER_MSEC)), dispatch_get_main_queue(), ^{
            self.callType = 1;
            [self.codeView.textField resignFirstResponder];
        });
    }
}


- (void)handlerKeyboardWillShowNotification:(NSNotification *)noti {
    NSLog(@"self.codeView.textField.isFirstResponder = %d", self.codeView.textField.isFirstResponder);
    if (!self.codeView.textField.isFirstResponder) {
        return;
    }
    
    _contentView.hidden = NO;
    
    NSDictionary *userInfo = [noti userInfo];
    CGFloat duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    CGFloat height = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    UIViewAnimationCurve curve = [userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue];
    
    [UIView setAnimationCurve:curve];
    [UIView animateWithDuration:duration animations:^{
        CGRect rect = self.contentView.frame;
        rect.origin.y = KScreenHeight- (self.contentView.frame.size.height + height);
        self.contentView.frame = rect;
        self.maskView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.4];
    }];
}

- (void)handlerKeyboardWillHideNotification:(NSNotification *)noti {
    
    if (!self.codeView.textField.isFirstResponder) {
        return;
    }
    
    NSDictionary *userInfo = [noti userInfo];
    CGFloat duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    UIViewAnimationCurve curve = [userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue];//动画曲线类型
    [UIView setAnimationCurve:curve];
    [UIView animateWithDuration:duration animations:^{
        CGRect rect = self.contentView.frame;
        rect.origin.y = KScreenHeight;
        self.contentView.frame = rect;
        self.maskView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
    } completion:^(BOOL finished) {
        [self dismissViewControllerAnimated:NO completion:^{
            if (self.callType == 1) {
                if (self.inputComplete) {
                    self.inputComplete(self.codeView.textField.text);
                }
            } else if (self.callType == 2) {
                if (self.changePassword) {
                    self.changePassword();
                }
            }
        }];
    }];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    // 检查是否是连续的空格
    if ([string isEqualToString:@" "] && [textField.text hasSuffix:@" "]) {
        return NO;
    }
    
    NSString *proposedText = [textField.text stringByReplacingCharactersInRange:range withString:string];
    
    NSCharacterSet *allowedCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 "];
    
    // 检查即将插入的字符是否都属于允许的字符集，且首字母不是空格
    if ([proposedText length] > 0) {
        unichar firstChar = [proposedText characterAtIndex:0];
        if (firstChar == ' ' || ![allowedCharacterSet characterIsMember:firstChar]) {
            return NO;
        }
    }
    
    return [[proposedText stringByTrimmingCharactersInSet:allowedCharacterSet] isEqualToString:@""];
}

- (void)textFieldDidChange:(QMUITextField *)textField {
    _OKButton.enabled = textField.text.length > 0;
}

- (UIModalPresentationStyle)modalPresentationStyle {
    return UIModalPresentationCustom;
}


- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}




@end
